package com.holi.hiteacher.data;

import com.holi.hiteacher.bean.EmailBean;
import com.holi.hiteacher.utils.MyApplication;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.RuntimeExceptionDao;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年01月09日 15:52
 * @version: 1.0
 */

public class DatabaseUtil {
    private static RuntimeExceptionDao<EmailBean, Integer> mDao;

    static {
        mDao = OpenHelperManager.getHelper(MyApplication.getContext(),
                DatabaseHelper.class).getEmailDao();
    }

    /**
     * 获取未读信息数目
     *
     * @return
     */
    public static int getUnreadCount() {
        int count = 0;

        CloseableIterator<EmailBean> it = mDao.iterator();

        while (it.hasNext()) {
            if (!it.next().isReaded()) {
                count++;
            }
        }

        try {
            it.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

//        OpenHelperManager.releaseHelper();

        return count;
    }

    public static EmailBean getEmailBean(int id) {
        EmailBean bean = mDao.queryForId(id);
        if (bean == null)
            throw new IllegalArgumentException("EmailBean id: " + id + " not exist.");
        return bean;
    }

    public static void updateEmailBean(EmailBean bean) {
        mDao.update(bean);
    }

    public static ArrayList<EmailBean> queryAllEmailBean() {
        return (ArrayList<EmailBean>) mDao.queryForAll();
    }
}
